#include "MemoryPool.h"
#include "HugePageAllocator.h"
#include <cstring>
#include <cassert>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>

MemoryPool::MemoryPool(size_t blockSize, size_t blockCount)
    : blockSize_(blockSize), blockCount_(blockCount)
{
    size_t totalSize = blockSize_ * blockCount_;
    memory_ = HugePageAllocator::allocate(totalSize);
    if (!memory_)
    {
        perror("Failed to allocate huge pages");
        exit(EXIT_FAILURE);        
    }
}

MemoryPool::~MemoryPool()
{
    HugePageAllocator::deallocate(memory_, blockSize_ * blockCount_);
}

void *MemoryPool::allocate(size_t memoryIdx)
{
    if(memoryIdx >= blockCount_)
    {
        fprintf(stderr, "[MemoryPool] Invalid memoryIdx: %zu\n", memoryIdx);
        return nullptr;
    }

    void *ptr = reinterpret_cast<char*>(memory_) + blockSize_ * memoryIdx;
    memset(ptr, 0x00, blockSize_);
    return ptr;
}
